# GPL3 or later

import os
import sys
import traceback
import time
import datetime
import random
import threading
import json
import simplematrixbotlib as botlib

import youtube
import commands
from ui import *


# Calculating today's data for volume voting!




session = {"bot":None,
           "room":None,
           "now_playing":None}

def files_manager():

    # This fucntion will run in it's own thread and manage downloading songs.
    while True:
        try:
            time.sleep(5)
            with open('stuff.json') as json_file: 
                stuff = json.load(json_file)

            for videoId in stuff.get("songs", {}):
                song = stuff.get("songs", {}).get(videoId, {})
                if not song.get("file"):

                    print("        [  "+clr["tbbu"]+"GETTING"+clr["norm"]+" ] "+videoId)

                    d = youtube.insure_song(videoId, videoId)

                    if d:

                        with open('stuff.json') as json_file: 
                            stuff = json.load(json_file)

                        stuff["songs"][videoId]["file"] = d
                        stuff["songs"][videoId]["timestamp"] = int(time.time())

                        with open('stuff.json', 'w') as fp:
                            json.dump(stuff, fp, indent=4)
        except:
            pass

# def playing_now():
#     try:
#         with open('stuff.json') as json_file: 
#             stuff = json.load(json_file)

#         if stuff.get("now_playing") != session["now_playing"]:

#             session["now_playing"] = stuff.get("now_playing")
#             m = "Now Playing: " + stuff.get("now_playing", "")
#             try:
#                 session["bot"].api.send_markdown_message(session["room"].room_id, m)
#             except:
#                 pass
            
#     except Exception as e:
#         print(e)    
                
t2 = threading.Thread(target=files_manager)
t2.setDaemon(True)
t2.start()

# t3 = threading.Thread(target=playing_now)
# t3.setDaemon(True)
# t3.start()

 #[   OKAY   ] 17yWeynOfOI | 03:32.0
# [  GETTING ] 17yWeynOfOI | 03:32.0

with open('stuff.json') as json_file: 
    stuff = json.load(json_file)

    
matrix_username = stuff["matrix"]["username"]
matrix_password = stuff["matrix"]["password"]
the_room     = stuff["matrix"]["room"]

print("Searching on the '"+the_room+"' room.")

server = "https://"+matrix_username[matrix_username.find(":")+1:]

creds = botlib.Creds(server, matrix_username, matrix_password)
bot = botlib.Bot(creds)
session["bot"] = bot
PREFIX = '!'

@bot.listener.on_message_event
async def echo(room, message):

    with open('stuff.json') as json_file: 
        stuff = json.load(json_file)
                
    new_date_format = "%Y/%m/%d"
    today = datetime.datetime.strftime(datetime.datetime.today(), new_date_format)
    for d in range(400):
        yesterday = datetime.datetime.strftime(datetime.datetime.today()-datetime.timedelta(days=d+1), new_date_format)
        if yesterday in stuff.get("volume", {}):
            break


        
    if room.name == the_room:


        
        session["room"] = room
        
        username = str(message.sender)
        
        if matrix_username != username:
            print("        [ "+clr["bold"]+clr["tbbu"]+"MESSAGE"+clr["norm"]+"  ] "+str(message).replace("\n", "\n                "))

        answer = commands.execute(username, message.body)
        if not answer:
            return
        sendis = ""
        for n, i in enumerate(answer.split("\n")):
            sendis = sendis+"\n"+i
            if n % 100 == 0:
                print("        [  "+clr["tbbu"]+"SENDING"+clr["norm"]+" ] "+sendis.replace("\n", "\n                  "))
                await bot.api.send_markdown_message(room.room_id, sendis)
                sendis = ""
                time.sleep(2)
        print("        [  "+clr["tbbu"]+"SENDING"+clr["norm"]+" ] "+sendis.replace("\n", "\n                  "))
        await bot.api.send_markdown_message(room.room_id, sendis)
        return


while True:
    try:


        
        bot.run()
    except:

        message = str(traceback.format_exc())
        
        print()
        print("        [  "+clr["tbrd"]+"ERROR!"+clr["norm"]+"  ]", message.replace("\n", "\n                      "))
        print()

